/*
	treeId tree的容器ID
	mode tree选择项的模式:默认单选select，多选check
	treeUrl 获取tree结构的路径
	dataUrl 获取tree选择项的路径
	isOpen 节点是否打开
	topName 最上级节点名称
*/
function initTree(treeId, settings, mode, treeUrl, dataUrl, isOpen, topName) {
    if (!mode) {
        mode = 'select';
    }
    if (!settings) {
        settings = getSettings(mode);
    }
    $.fn.zTree.init($("#" + treeId), settings, getTree(treeUrl, isOpen, topName));
    if (dataUrl) {
        initTreeDatas(treeId, dataUrl, mode);
    }
}

function getTree(url, isOpen, topName) {
	var root = {
		id : 0,
		name : topName ? topName : 'root',
		open : isOpen === true || isOpen === undefined || isOpen === ''
	};

	$.ajax({
		type : 'get',
		url : url,
		contentType : "application/json; charset=utf-8",
		async : false,
		success : function(data) {
			var length = data.length;
			var children = [];
			for (var i = 0; i < length; i++) {
				var d = data[i];
				var node = createNode(d);
				children[i] = node;
			}
			root.children = children;
		}
	});

	return root;
}

function initTreeDatas(treeId, url, mode){
	$.ajax({
		type : 'get',
		url : url,
		success : function(json) {
            if (json.code === 0) {
                var data = json.data;
                var length = data.length;
                var checkIds = [];
                if (!mode || mode === 'select') {
                    checkIds.push(data['id']);
                } else if (mode === 'check') {
                    for(var i=0; i<length; i++){
                        checkIds.push(data[i]['id']);
                    }
                }
                initTreeCheck(treeId, mode, checkIds);
            }
		}
	});
}

function initTreeCheck(treeId, mode, checkIds) {
	var treeObj = $.fn.zTree.getZTreeObj(treeId);
    if (mode === 'select') {
    	var node = treeObj.getNodeByParam("id", checkIds[0], null);
        treeObj.selectNode(node, true, false);
    } else {
        var length = checkIds.length;
        if(length > 0){
            var node = treeObj.getNodeByParam("id", 0, null);
            treeObj.checkNode(node, true, false);
        }

        for(var i=0; i<length; i++){
            var node = treeObj.getNodeByParam("id", checkIds[i], null);
            treeObj.checkNode(node, true, false);
        }
    }

	
}

function getTreeCheckedIds(treeId){
	var treeObj = $.fn.zTree.getZTreeObj(treeId);
	var nodes = treeObj.getCheckedNodes(true);
	
	var length = nodes.length;
	var ids = [];
	for(var i=0; i<length; i++){
		var n = nodes[i];
		var id = n['id'];
		ids.push(id);
	}
	
	return ids;
}

function getTreeSelectedId(treeId){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    var nodes = treeObj.getSelectedNodes();

    var length = nodes.length;
    var ids = [];
    for(var i=0; i<length; i++){
        var n = nodes[i];
        var id = n['id'];
        ids.push(id);
    }

    return ids;
}

function createNode(d) {
	var id = d['id'];
	var pId = d['parentId'];
	var name = d['name'];
	var child = d['child'];

	var node = {
		open : true,
		id : id,
		name : name,
		pId : pId,
	};

	if (child != null) {
		var length = child.length;
		if (length > 0) {
			var children = [];
			for (var i = 0; i < length; i++) {
				children[i] = createNode(child[i]);
			}

			node.children = children;
		}

	}
	return node;
}

function initParentMenuSelect(){
	$.ajax({
        type : 'get',
        url : '/permissions/parents',
        async : false,
        success : function(json) {
            if (json.code === 0) {
                var data = json.data;
                var select = $("#parentId");
                select.append("<option value='0'>root</option>");
                for(var i=0; i<data.length; i++){
                    var d = data[i];
                    var id = d['id'];
                    var name = d['name'];

                    select.append("<option value='"+ id +"'>" +name+"</option>");
                }
            }
        }
    });
}

function getSettings(mode) {
	let settings;
    if (!mode || mode === 'select') {
        settings = {
            async : {
                enable : true,
            },
            data : {
                simpleData : {
                    enable : true,
                    idKey : "id",
                    pIdKey : "pId",
                    rootPId : 0
                }
            },
            callback : {
                onClick : zTreeOnClick
            }
        };
    } else if (mode === 'check') {
        settings = {
            check : {
                enable : true,
                chkboxType : {
                    "Y" : "ps",
                    "N" : "ps"
                }
            },
            async : {
                enable : true,
            },
            data : {
                simpleData : {
                    enable : true,
                    idKey : "id",
                    pIdKey : "pId",
                    rootPId : 0
                }
            },
            callback : {
                onCheck : zTreeOnCheck
            }
        };
    }
	return settings;
}

function zTreeOnCheck(treeId, treeNode) {

}

function zTreeBeforeClick(treeId, treeNode) {
    // console.log(treeNode.id + ", " + treeNode.name);
    if (treeNode.isParent) {
        layer.msg('不能选择父节点', {
            time: 1000
        });
        return false;
    }
}

function zTreeOnClick(event, treeId, treeNode) {
    // console.log(treeNode.id + ", " + treeNode.name);
    parent[elementId] = treeNode.id;
    parent[elementName] = treeNode.name;
    parent['isSelected'] = true;
}